package com.zzh.webhook.service;

import com.zzh.webhook.config.ProjectConfig;
import com.zzh.webhook.utils.CommandExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
@RequiredArgsConstructor
public class DockerService {
    
    private final CommandExecutor commandExecutor;
    private final ProjectConfig projectConfig;
    
    /**
     * 为指定模块构建Docker镜像
     * 
     * @param moduleName 模块名称
     * @return 镜像ID
     */
    public String buildImage(String moduleName) throws IOException {
        String localPath = projectConfig.getGit().getLocalPath();
        String modulePath = String.format("%s/%s", localPath, moduleName);
        
        log.info("Building Docker image for module: {}", moduleName);
        
        // 执行模块目录下的构建脚本
        String buildCommand = "./build-docker.sh";
        String result = commandExecutor.execute(buildCommand, modulePath);
        
        // 从构建结果中提取镜像ID
        // 这里假设构建脚本会输出镜像ID
        String imageId = result.trim();
        log.info("Built Docker image: {} for module: {}", imageId, moduleName);
        
        return imageId;
    }
    
    /**
     * 创建并启动Docker容器
     * 
     * @param moduleName 模块名称
     * @param imageId 镜像ID
     */
    public void createAndStartContainer(String moduleName, String imageId) throws IOException {
        ProjectConfig.Docker.DockerModule dockerModule = projectConfig.getDocker().getModules().get(moduleName);
        
        if (dockerModule == null) {
            log.warn("No Docker configuration found for module: {}", moduleName);
            return;
        }
        
        int internalPort = dockerModule.getPortInternal();
        int externalPort = dockerModule.getPortExternal();
        
        log.info("Creating and starting Docker container for module: {} with image: {}", moduleName, imageId);
        
        // 停止并删除旧容器（如果存在）
        String containerName = "app-" + moduleName;
        String stopCommand = String.format("docker stop %s || true", containerName);
        commandExecutor.execute(stopCommand, null);
        
        String removeCommand = String.format("docker rm %s || true", containerName);
        commandExecutor.execute(removeCommand, null);
        
        // 创建并启动新容器
        String runCommand = String.format(
                "docker run -d --name %s -p %d:%d %s",
                containerName, externalPort, internalPort, imageId);
        
        String containerId = commandExecutor.execute(runCommand, null).trim();
        log.info("Started Docker container: {} for module: {}", containerId, moduleName);
    }
    
    /**
     * 检查容器健康状态
     * 
     * @param moduleName 模块名称
     * @return 容器是否健康
     */
    public boolean checkContainerHealth(String moduleName) throws IOException {
        String containerName = "app-" + moduleName;
        
        log.info("Checking health of container: {}", containerName);
        
        String checkCommand = String.format("docker inspect --format='{{.State.Running}}' %s", containerName);
        String result = commandExecutor.execute(checkCommand, null).trim();
        
        boolean isRunning = "true".equalsIgnoreCase(result);
        log.info("Container {} is running: {}", containerName, isRunning);
        
        return isRunning;
    }
} 